package com.zjdiepu.www.manage.api.yw;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.text.ParseException;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.PhoneStatus;
import com.zjdiepu.www.base.enums.status.TongrongStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.ZhppDateUtil;
import com.zjdiepu.www.commpent.RedisObjectClient;
import com.zjdiepu.www.ibiz.base.IDpBaseDealerInfoService;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.fk.IFkAuditListService;
import com.zjdiepu.www.ibiz.other.IOtherAuditInfoService;
import com.zjdiepu.www.ibiz.system.IBaseBusiUnitService;
import com.zjdiepu.www.ibiz.system.IBaseSalersmanService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.ibiz.yw.IYwTongrongService;
import com.zjdiepu.www.ibiz.zpp.FengKongShenHeService;
import com.zjdiepu.www.model.base.dto.DpBaseDealerInfo;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.fk.dto.FkAuditList;
import com.zjdiepu.www.model.other.dto.OtherAuditInfo;
import com.zjdiepu.www.model.system.dto.BaseBusiUnit;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwTongrong;
import com.zjdiepu.www.model.yw.ext.YwTongrongExt;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;

/**
 * 通融申请Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月09日 09时29分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "YwTongrongController", produces="application/json;charset=UTF-8")
@Api(tags = {"通融申请"}, produces="application/json;charset=UTF-8")
public class YwTongrongController extends BaseController {
    @Resource
    private IYwTongrongService ywTongrongService;
    @Resource
    private IYwBusinessService ywBusinessService;
    @Resource
    private FengKongShenHeService fengKongShenHeService;
    @Resource
    private ICachedDictionaryService cachedDictionaryService;
    @Resource
	private IOtherAuditInfoService otherAuditInfoService;
    @Resource
    private IBaseSalersmanService baseSalersmanService;
    @Resource
    private IBaseBusiUnitService baseBusiUnitService;
    @Resource
    private IDpBaseDealerInfoService baseDealerInfoService;
    @Resource
    private IFkAuditListService fkAuditListService;
    @Resource
    private RedisObjectClient redisObjectClient;

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增通融申请 <br/>
     * @param ywTongrong
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增通融申请", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute YwTongrong ywTongrong) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywTongrong.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywTongrong.setModifierName(currentUser.getName());
        ywTongrongService.saveUpdateAndDelete(ywTongrong, OperateType.add);
        fengKongShenHeService.diepuFengKongShenTrsh(currentUser,ywTongrong.getBusiId(),ModeIDType.TRSH.getCode());
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除通融申请<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除通融申请", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywTongrongService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用通融申请<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用通融申请", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywTongrongService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用通融申请<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用通融申请", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywTongrongService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改通融申请 <br/>
     * @param ywTongrong
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改通融申请", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute YwTongrong ywTongrong) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywTongrong.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywTongrong.setModifierName(currentUser.getName());
    	ywTongrongService.saveUpdateAndDelete(ywTongrong, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询通融申请<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询通融申请", response = YwTongrong.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       YwTongrong ywTongrong = ywTongrongService.selectById(id);
       if(null == ywTongrong) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(ywTongrong);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询通融申请 <br/>
     * @param ywTongrongExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询通融申请",response = YwTongrong.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute YwTongrongExt ywTongrongExt){
        ywTongrongExt.notDeleted();
        PageVo page = getPage(ywTongrongExt);
        int records = ywTongrongService.countByExt(ywTongrongExt);
        page.setRecords(records);
        if (records > 0) {
            List<YwTongrong> ywTongrongs = ywTongrongService.selectByExt(ywTongrongExt);
            page.setRows(ywTongrongs);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

    @ApiOperation(value = "通融申请新增-修改业务表状态-待审批列表状态修改", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "tongrong", method = RequestMethod.POST)
    public ApiResponse tongrong(@Validated(Add.class) @ModelAttribute YwTongrong ywTongrong) {
    	//通融申请新增
    	AbstractSysUser currentUser = getCurrentUser();
    	ywTongrong.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywTongrong.setModifierName(currentUser.getName());
    	ywTongrong.setStatusTongrong(TongrongStatus.TONGRONGING.getCode());
        ywTongrongService.saveUpdateAndDelete(ywTongrong, OperateType.add);
//        fengKongShenHeService.fengKongShenTrsh(currentUser,ywTongrong.getBusiId(),ModeIDType.TRQYJLSH.getCode());
        FkAuditList fkAuditList= new FkAuditList();
    	fkAuditList.setBusiId(ywTongrong.getBusiId());
    	fkAuditList.setModeId(ModeIDType.TRQYJLSH.getCode());
    	fkAuditList.setSource("通融申请");
    	YwBusiness ywbusiness=ywBusinessService.selectById(ywTongrong.getBusiId());
    	if(ywbusiness!=null){
    		fkAuditList.setBusiConfirmTime(ywbusiness.getSubmitTime());
    		fkAuditList.setLoanAmount(ywbusiness.getSignLoanAmount());
    		fkAuditList.setChannelType(ywbusiness.getChannelType());
    		fkAuditList.setChannelTypeName(cachedDictionaryService.getName(String.valueOf(fkAuditList.getChannelType()), DataDicType.CHANNEL_TYPE));
    		fkAuditList.setChannelStatus(ywbusiness.getChannelStatus());
    		fkAuditList.setChannelStatusName(cachedDictionaryService.getName(String.valueOf(fkAuditList.getChannelStatus()), DataDicType.CHANNEL_STATUS));
    		fkAuditList.setDealer(ywbusiness.getDealerId());
			BaseSalersman baseSalersman=baseSalersmanService.selectById(ywbusiness.getSalesmanId());
			if(baseSalersman!=null && baseSalersman.getUnitId()!=null){
				fkAuditList.setSalersmanName(baseSalersman.getName());
				BaseBusiUnit baseBusiUnit=baseBusiUnitService.selectById(baseSalersman.getUnitId());
				if(baseBusiUnit !=null){
					fkAuditList.setDepartmentName(baseBusiUnit.getOrgName());
				}
			}
    		DpBaseDealerInfo baseDealerInfo=baseDealerInfoService.selectById(ywbusiness.getDealerId());
    		if(baseDealerInfo!=null){
    			fkAuditList.setDealer(baseDealerInfo.getDealerName());
    		}
    		fkAuditList.setCusName(ywbusiness.getCustomerName());
    		fkAuditList.setCusIdno(ywbusiness.getCustomerNo());
    		fkAuditList.setBankname(cachedDictionaryService.getName(ywbusiness.getBankLoan(),DataDicType.LOAN_BANK));
    		fkAuditList.setStatusList(1);
    	}
    	fkAuditListService.saveUpdateAndDelete(fkAuditList, OperateType.add);
        
        //修改业务表状态
        YwBusiness ywBusiness = new YwBusiness();
    	ywBusiness.setId(ywTongrong.getBusiId());
    	ywBusiness.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusiness.setModifierName(currentUser.getName());
    	ywBusiness.setTongrongStatus(TongrongStatus.TONGRONGING.getCode());
        ywBusinessService.saveUpdateAndDelete(ywBusiness, OperateType.edit);
        
       
//    	ywBusinessService.insertFkAuditList(ywTongrong.getBusiId(),ModeIDType.TRSH.getCode(),currentUser);
        return ApiResponse.success(true);
    }
    @ApiOperation(value = "通融申请列表", response = Boolean.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "selectMulitList", method = RequestMethod.POST)
    public ApiResponse selectMulitList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser sysUser = (SysUser)getCurrentUser();
        PageVo page = getPage(ywBusinessQueryRequest);
        ywBusinessQueryRequest.setBaseWhere();
        ywBusinessQueryRequest.setBankLoan(sysUser.getLoanBank());
        ywBusinessQueryRequest.setCodeUnits(sysUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
        ywBusinessQueryRequest.setBusiStatusMore(BusiStatus.FENG_KONG_ZONG_JIAN_SHEN_HE_SHI_BAI.getCode());
        ywBusinessQueryRequest.setBusiStatusLess(BusiStatus.CHU_SHEN_DAN_CHU_SHEN_SHI_BAI.getCode());
        ywBusinessQueryRequest.setTongrongStatus(TongrongStatus.NOT_TONGRONG.getCode());
        ywBusinessQueryRequest.setPhoneStatusLess(PhoneStatus.PHONE_1_FAIL.getCode());
        ywBusinessQueryRequest.setPhoneStatusMore(PhoneStatus.PHONE_2_FAIL.getCode());
        int records = ywTongrongService.countMultiByExt(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesssList = ywTongrongService.selectMultiByExt(ywBusinessQueryRequest);
            redisObjectClient.execute(new RedisCallback<Boolean>() {

				@Override
				public Boolean doInRedis(RedisConnection redisConnection)
						throws DataAccessException {
					OtherAuditInfo otherAuditInfo=new OtherAuditInfo();
					for (YwBusiness ywBusiness : ywBusinesssList) {
						otherAuditInfo= new OtherAuditInfo();
						otherAuditInfo.setOrderSql(" created desc");
						otherAuditInfo.setBusiId(ywBusiness.getId());
						otherAuditInfo.setAuditStatus("3");
						otherAuditInfo=otherAuditInfoService.selectRefined(otherAuditInfo);
						if(otherAuditInfo !=null){
							ywBusiness.setReasonAuditFalseName(otherAuditInfo.getReasonAuditFalseName());
							try {
								ywBusiness.setTimeAudit(ZhppDateUtil.stampConvertDate(otherAuditInfo.getCreated(),"yyyy-MM-dd"));
							} catch (ParseException e) {
								e.printStackTrace();
							}
						}
						String channelType = ywBusiness.getChannelType();
						SimpleDataDictionary channelTypeDic = redisObjectClient.hGet(redisConnection, SimpleDataDictionary.class.getSimpleName(),  channelType, DataDicType.CHANNEL_TYPE.getCode());
						ywBusiness.setChannelTypeDisplay(channelTypeDic == null ? "" : channelTypeDic.getName());
						
						Integer channelStatus = ywBusiness.getChannelStatus();
						SimpleDataDictionary channelStatusDic = redisObjectClient.hGet(redisConnection, SimpleDataDictionary.class.getSimpleName(),  String.valueOf(channelStatus), DataDicType.CHANNEL_STATUS.getCode());
						ywBusiness.setChannelStatusDisplay(channelStatusDic == null ? "" : channelStatusDic.getName());
						
						String bankLoan = ywBusiness.getBankLoan();
						SimpleDataDictionary bankLoanDic = redisObjectClient.hGet(redisConnection, SimpleDataDictionary.class.getSimpleName(),  bankLoan, DataDicType.LOAN_BANK.getCode());
						ywBusiness.setBankLoanDisplay(bankLoanDic == null ? "" : bankLoanDic.getName());
					}
					page.setRows(ywBusinesssList);
					return true;
				}
			});
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
    	return ApiResponse.success(page);
    }
} 
